package com.springboot.bookmanegersystem.interceptor;

import com.springboot.bookmanegersystem.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-05-12
 * Time: 19:13
 */
@Component
public class IdentityInterceptor implements HandlerInterceptor {

    private static final String USERINFO = "USERINFO";

    // 目标方法执行前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前用户是否为管理员
        // 1)判断用户是否登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(USERINFO) == null) {
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(401); // 用户未登录
            response.getOutputStream().write("用户未登录".getBytes(StandardCharsets.UTF_8));
            return false;
        }
        // 2)判断用户身份
        UserInfo userInfo = (UserInfo) session.getAttribute(USERINFO);
        if (userInfo.getIdentity() == 0) {
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(403); // 用户无权限
            response.getOutputStream().write("用户无权限".getBytes(StandardCharsets.UTF_8));
            return false;
        }
        return true;
    }

    // 目标方法执行后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
